package cn.project.infrastructure.persistent.repository;

import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy;
import cn.project.domain.credit.model.aggregate.TradeAggregate;
import cn.project.domain.credit.model.entity.CreditAccountEntity;
import cn.project.domain.credit.repository.ICreditRepository;
import cn.project.infrastructure.event.EventPublisher;
import cn.project.infrastructure.persistent.dao.ITaskDao;
import cn.project.infrastructure.persistent.dao.IUserCreditAccountDao;
import cn.project.infrastructure.persistent.dao.IUserCreditOrderDao;
import cn.project.infrastructure.persistent.po.UserCreditAccount;
import cn.project.infrastructure.redis.IRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @author xu
 * @description 用户积分仓储
 * @date 2025/8/8
 */
@Slf4j
@Repository
public class CreditRepository implements ICreditRepository {
    @Resource
    private IRedisService redisService;
    @Resource
    private IUserCreditAccountDao userCreditAccountDao;
    @Resource
    private IUserCreditOrderDao userCreditOrderDao;
    @Resource
    private ITaskDao taskDao;
    @Resource
    private IDBRouterStrategy dbRouter;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private EventPublisher eventPublisher;
    @Override
    public void saveUserCreditTradeOrder(TradeAggregate tradeAggregate) {

    }

    @Override
    public CreditAccountEntity queryUserCreditAccount(String userId) {
        UserCreditAccount userCreditAccountReq = new UserCreditAccount();
        userCreditAccountReq.setUserId(userId);
        try {
            dbRouter.doRouter(userId);
            UserCreditAccount userCreditAccount = userCreditAccountDao.queryUserCreditAccount(userCreditAccountReq);
            BigDecimal availableAmount = BigDecimal.ZERO;
            if (userCreditAccount != null) {
                availableAmount = userCreditAccount.getAvailableAmount();
            }
            return CreditAccountEntity.builder().userId(userId).adjustAmount(availableAmount).build();
        } finally {
            dbRouter.clear();
        }
    }


}
